package handler

import (
	"context"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/garyburd/redigo/redis"
	"ihome/models"
	"ihome/utils"
	"strconv"

	"github.com/micro/go-micro/util/log"

	getHouseInfo "ihome/proto/getHouseInfo"
)

type GetHouseInfo struct{}

func (e *GetHouseInfo) SrvGetHouseInfo(ctx context.Context, req *getHouseInfo.Request, rsp *getHouseInfo.Response) error {
	logs.Info("获取房屋信息 SrvGetHouseInfo /api/v1.0/houses/:id")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}
	sessionId := req.SessionId
	userIdObj := bm.Get(sessionId + "user_id")
	userId, _ := redis.Int(userIdObj, nil)

	houseId, _ := strconv.Atoi(req.Id)

	house := models.House{Id: houseId}
	o := orm.NewOrm()
	err = o.Read(&house)

	if err != nil {
		logs.Info("查询房屋失败")
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	o.LoadRelated(&house, "Area")
	o.LoadRelated(&house, "User")
	o.LoadRelated(&house, "Images")
	o.LoadRelated(&house, "Facilities")

	houseMix, err := json.Marshal(house)
	rsp.UserId = int64(userId)
	rsp.HouseData = houseMix

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *GetHouseInfo) Stream(ctx context.Context, req *getHouseInfo.StreamingRequest, stream getHouseInfo.GetHouseInfo_StreamStream) error {
	log.Logf("Received GetHouseInfo.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&getHouseInfo.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *GetHouseInfo) PingPong(ctx context.Context, stream getHouseInfo.GetHouseInfo_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&getHouseInfo.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
